import requests
import json
import config

def to_json(str):
	return json.loads(str)


def get_access_token():
	"""
　　获取全局接口凭证，默认有效2小时，
	"""
	result = requests.get(
		url="https://api.weixin.qq.com/cgi-bin/token",
		params={
			"grant_type": "client_credential",
			"appid": "",
			"secret": ""
		}
	).json()
	if result.get("access_token"):
		access_token = result.get("access_token")
	else:
		access_token = None
	return access_token


def sendmsg(openid,a_Token,msg):
	"""
	发送消息给用户
	:param openid: 用户ID
	:param msg: 消息内容
	:return:
	"""
	send_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"
	body = {
		"touser": openid,
		"msgtype": "text",
		"text": {
			"context": msg
		}
	}
	s_req = requests.post(send_url,params={"access_token":a_Token} , data=bytes((body), encoding="UTF-8"))


def send_module_msg(a_Token, openid, t_id, msg):
	"""
	发送模板消息
	:param a_Token:
	:param openid:
	:param t_id:
	:param msg:
	:return:  返回状态 json
	"""
	send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send"
	para = {"access_token":a_Token}
	body = {
		"touser": openid,
		"topcolor": "#FE0000",
		"template_id":t_id,
		"data":msg
	}
	r = requests.post(send_url, params=para, json=body)
	return r.content


def get_module_id(a_Token):
	para_m_url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template"
	req_m_id = requests.post(para_m_url, params={"access_token": a_Token})
	module_list = to_json(req_m_id.content)
	module_id = module_list["template_list"][0]["template_id"]
	return module_id
